package _20250305;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThread4 {
    /**
     * 有两个线程，线程 A 对变量count进行 100 次加 1 操作，线程 B 对变量count进行 100 次减 1 操作，实现代码保证操作完成后count的值为 0 。
     */
    private static int count=0;
    private static final Object lock=new Object();
    private static AtomicInteger count1=new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {

        Thread addCount= new Thread(new AddCount());
        Thread subCount = new Thread(new SubCount());
        addCount.start();
        subCount.start();
        //join方法能等待方法执行完成
        addCount.join();
        subCount.join();
        System.out.println(count);
    }

    /**
     * 增加count
     */
    private static class AddCount implements Runnable {
        @Override
        public void run() {

                for (int i = 0; i < 100; i++) {
//                    synchronized (lock) {
//                        count++;
                    count1.incrementAndGet(); // 原子加 1
                    }
                }

        }

    /**
     * 减少count
     */
    private static class SubCount implements Runnable {
        @Override
        public void run() {
                for (int i = 0; i < 100; i++) {
//                    synchronized (lock) {
//                        count--;
                    count1.decrementAndGet();
                    }
                }
        }
    }

